import 'package:flutter/material.dart';
import '../../core/base/base_view_model.dart';
import '../../core/http/http_client.dart';
import 'order_model.dart';

class OrderListViewModel extends BaseViewModel {
  final _httpClient = HttpClient();
  List<OrderModel> orders = [];

  Future<void> fetchOrders() async {
    try {
      setBusy(true);
      final response = await _httpClient.get('/orders');
      
      if (response.code == 200) {
        orders = (response.data as List)
            .map((json) => OrderModel.fromJson(json))
            .toList();
        notifyListeners();
      } else {
        setError('获取订单列表失败');
      }
    } catch (e) {
      setError('获取订单列表失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  Future<void> updateOrderStatus(String id, String status) async {
    try {
      setBusy(true);
      final response = await _httpClient.patch('/orders/$id', data: {
        'status': status,
      });
      
      if (response.code == 200) {
        final index = orders.indexWhere((order) => order.id == id);
        if (index != -1) {
          orders[index] = OrderModel.fromJson(response.data);
          notifyListeners();
        }
      } else {
        setError('更新订单状态失败');
      }
    } catch (e) {
      setError('更新订单状态失败：${e.toString()}');
    } finally {
      setBusy(false);
    }
  }

  void searchOrders(String keyword) {
    // TODO: 实现订单搜索功能
  }
}